import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, initRouterNode } from '@/utils/auth'
import router, { resetRouter, constantRoutes } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  userName: '',
  userId: '',
  realName: '',
  structurName: '',
  avatarImgPath: '',
  access: '',
  hasGetInfo: false,
  unreadCount: 0,
  messageUnreadList: [],
  messageReadedList: [],
  messageTrashList: [],
  messageContentStore: {},
  userInfo: {},
  routers: constantRoutes,
  menuList: constantRoutes,
  appRouterList: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  setAvatar: (state, avatarPath) => {
    state.avatarImgPath = avatarPath
  },
  setUserId: (state, id) => {
    state.userId = id
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  setUserName: (state, name) => {
    state.userName = name
  },
  setRealName: (state, name) => {
    state.realName = name
  },
  setStructurName: (state, name) => {
    state.structurName = name
  },
  setAccess: (state, access) => {
    state.access = access
  },
  setToken: (state, token) => {
    setToken(token)
  },
  setHasGetInfo: (state, status) => {
    state.hasGetInfo = status
  },
  setMessageCount: (state, count) => {
    state.unreadCount = count
  },
  setMessageUnreadList: (state, list) => {
    state.messageUnreadList = list
  },
  setMessageReadedList: (state, list) => {
    state.messageReadedList = list
  },
  setMessageTrashList: (state, list) => {
    state.messageTrashList = list
  },
  updateMessageContentStore: (state, { msg_id, content }) => {
    state.messageContentStore[msg_id] = content
  },
  moveMsg: (state, { from, to, msg_id }) => {
    const index = state[from].findIndex(_ => _.msg_id === msg_id)
    const msgItem = state[from].splice(index, 1)[0]
    msgItem.loading = false
    state[to].unshift(msgItem)
  },
  updateAppRouter: (state, routes) => {
    state.appRouterList = routes
    state.routers.push(...routes)
    router.addRoutes(routes)
  },
  updateMenulist: (state, routes) => {
    state.menuList = routes
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { userName, password, appId, endpoint } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName, password, appId, endpoint }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      try {
        // getInfo().then(res => {
        //   commit('setAvatar', res.headImg)
        //   const constRoutes = []
        //   // console.log(res.menus)
        //   constRoutes.push({
        //     path: '/home',
        //     component: () => import('@/views/home/index'),
        //     name: 'home',
        //     children: [],
        //     meta: { title: '首页', icon: 'home', affix: true }
        //   })
        //   initRouterNode(constRoutes, res.menus, res.resFunctions, true)

        //   // console.log(constRoutes)
        //   commit('updateAppRouter', constRoutes)
        //   // 刷新界面菜单
        //   // commit('updateMenulist', constantRoutes)
        //   commit('setHasGetInfo', true)
        //   commit('setUserName', res.userName)
        //   commit('setRealName', res.realName)
        //   commit('setStructurName', res.structurName)
        //   commit('setUserId', res.userId)
        //   commit('setUserInfo', res)
        //   resolve(res)
        // }).catch(err => {
        //   reject(err)
        // })
        // const pageRoutes = constantRoutes.filter(item => {
        //   return item.name === 'layout'
        // })
        // commit('updateMenulist', pageRoutes.children)
      } catch (error) {
        reject(error)
      }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
